<template>
	<!--物资管理-物资列表-详情弹窗-表单-->
	<a-spin :spinning="confirmLoading">
		<j-form-container>
			<!-- 主表单区域 -->
			<a-form-model ref="form" :model="queryParam" :rules="validatorRules" slot="detail"
				@keyup.enter.native="searchQuery">
				<a-row>
					<a-col :span="12">
						<a-form-model-item label="时间" :labelCol="labelCol2" :wrapperCol="wrapperCol2"
							style="margin-bottom: 10px;">
							<div style="display: flex;align-items: center;">
								<j-date v-model="queryParam.queryStartTime" :showTime="true"
									date-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择开始时间"></j-date>
								<span style="width: 10px">~</span>
								<j-date v-model="queryParam.queryEndTime" :showTime="true"
									date-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择结束时间"></j-date>
							</div>
						</a-form-model-item>
					</a-col>

					<a-col :span="6">
						<a-form-model-item style="margin-bottom: 10px;" label="物资名称" :labelCol="labelCol"
							:wrapperCol="wrapperCol" prop="name">
							<a-input v-model="queryParam.platformProductName" placeholder="请输入物资名称"></a-input>
						</a-form-model-item>
					</a-col>
					<a-col :span="6">
						<a-form-model-item label="型号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="model"
							style="margin-bottom: 10px;">
							<a-input v-model="queryParam.model" placeholder="请输入型号"></a-input>
						</a-form-model-item>
					</a-col>
				</a-row>

				<a-row>
					<a-col :span="6">
						<a-form-model-item label="库房" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="warehouseName"
							style="margin-bottom: 10px;">
							<a-input v-model="queryParam.warehouseName" placeholder="请输入库房名称"></a-input>
						</a-form-model-item>
					</a-col>
					<a-col :span="6">
						<a-form-item label="类型" :labelCol="labelCol" :wrapperCol="wrapperCol"
							style="margin-bottom: 10px;">
							<a-select placeholder="请选择入库出库选项" v-model="queryParam.type">
								<a-select-option value="1">入库</a-select-option>
								<a-select-option value="2">出库</a-select-option>
							</a-select>
						</a-form-item>
					</a-col>
					
					<a-col :span="6">
						<a-form-item label="填单人" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="userName" style="margin-bottom: 10px;">
							<a-input placeholder="请输入填单人" v-model="queryParam.userName"
								@input="tolink('input_userName',$event)"></a-input>
						</a-form-item>
					</a-col>
					<a-col :span="6">
						<a-form-item label="" :labelCol="labelCol" :wrapperCol="wrapperCol"
							style="margin-bottom: 10px;">
							<a-button type="primary" @click="searchQuery1" icon="search"
								style="margin-left: 30px;">查询</a-button>
							<a-button type="primary" @click="searchReset1" icon="reload"
								style="margin-left: 20px">重置</a-button>
						</a-form-item>
					</a-col>
				</a-row>
			</a-form-model>
		</j-form-container>
		<!-- 子表单区域 -->
		<div>

			<a-table ref="table" size="middle" bordered rowKey="id" dragSort class="j-table-force-nowrap"
				:scroll="{ x: true }" :columns="columns" :dataSource="dataSources" :pagination="ipagination"
				:loading="loading" v-bind="tableProps"
				:rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
				@change="handleTableChange">
				<template slot="imgSlot" slot-scope="text, record">
					<template v-if="record.type != '3'">
						<span v-if="!text" style="font-size: 12px; font-style: italic">无图片</span>
						<imgs-preview v-else :imgs="text" imgH="25px"></imgs-preview>
					</template>
				</template>
				<template slot="number" slot-scope="text,record">
					<span>{{text}}</span>
				</template>
				<span slot="action" slot-scope="text, record">
					<a @click="handleEdits(record)">{{record.type == '1'?'修改入库':record.type == '2'?'修改出库':''}}</a>
					<a-divider type="vertical" />
					<a-popconfirm title="确定删除吗？" @confirm="handleDelete(record.id)">
						<a>删除</a>
					</a-popconfirm>
					<!--<a v-if="record.type_dictText == '出库'" @click="handleG(record)"> 修改出库</a> -->
				</span>
			</a-table>
			<div class="count">

			</div>
		</div>
		<wt-materials-xiu-modal :id="this.id" ref="modalForm1" @ok="modalFormOk" />
		<wt-materials-gai-modal :id="this.id" ref="modalForm2" @ok="modalFormOk" />
		<wt-materials-detail-modal ref="modalForm" @ok="modalFormOk" />
	</a-spin>
</template>

<script>
	import {
		JVxeTableModelMixin
	} from '@/mixins/JVxeTableModelMixin.js'
	import {
		getRefPromise,
		VALIDATE_FAILED
	} from '@/components/jeecg/JVxeTable/utils/vxeUtils.js'
	import JFormContainer from '@/components/jeecg/JFormContainer'
	import {
		JeecgListMixin
	} from '@/mixins/JeecgListMixin'
	import WtMaterialsXiuModal from './WtMaterialsXiuModal'
	import WtMaterialsGaiModal from './WtMaterialsGaiModal'
	import WtMaterialsDetailModal from './WtMaterialsDetailModal'
	import JDate from '@/components/jeecg/JDate'
	import {
		filterObj
	} from '@/utils/util'
	import {
		httpAction,
		getAction,
		postAction
	} from '@/api/manage'
	export default {
		name: 'WtMaterialsForm',
		mixins: [JVxeTableModelMixin, JeecgListMixin],
		components: {
			JFormContainer,
			WtMaterialsXiuModal,
			WtMaterialsGaiModal,
			JDate,
			WtMaterialsDetailModal
		},
		data() {
			return {
				id: '',
				confirmLoading: false,
				ipagination: {
					current: 1,
					pageSize: 10,
					pageSizeOptions: ['10', '20', '30'],
					showTotal: (total, range) => {
						return range[0] + '-' + range[1] + ' 共' + total + '条'
					},
					showQuickJumper: true,
					showSizeChanger: true,
					total: 0,
				},
				labelCol: {
					xs: {
						span: 24
					},
					sm: {
						span: 6
					},
				},
				wrapperCol: {
					xs: {
						span: 24
					},
					sm: {
						span: 18
					},
				},
				labelCol2: {
					xs: {
						span: 24
					},
					sm: {
						span: 3
					},
				},
				wrapperCol2: {
					xs: {
						span: 24
					},
					sm: {
						span: 21
					},
				},
				queryParam: {
					materialsId: this.id,
					platformProductName: '',
					warehouseName: '',
					queryStartTime: '',
					queryEndTime: '',
					type: '',
				},
				total2: {
					putTotal: '',
					outTotal: '',
				},
				treeData1: [],
				// model:{
				//   queryEndTime:'',
				//   queryStartTime:'',
				//   materialsId:this.id
				//  },
				// 新增时子表默认添加几行空数据
				addDefaultRowNum: 0,
				validatorRules: {},
				total1: [],
				refKeys: ['wtMaterialsDetail'],
				tableKeys: ['wtMaterialsDetail'],
				activeKey: 'wtMaterialsDetail',

				columns: [{
						title: '序号',
						dataIndex: 'rowIndex',
						key: 'rowIndex',
						width: 60,
						align: 'center',
						customRender: function(text, r, index) {
							return (text !== '入库合计') ? (parseInt(index) + 1) : text
						}
					},
					{
						title: '日期',
						align: 'center',
						dataIndex: 'createTime',
					},
					{
						title: '送货单号/领料单号',
						align: 'center',
						dataIndex: 'orderNo',
					},
					{
						title: '物资名称',
						align: 'center',
						dataIndex: 'platformProductName',
					},
					{
						title: '型号',
						align: 'center',
						dataIndex: 'model',
					},

					{
						title: '库房',
						align: 'center',
						dataIndex: 'warehouseName',
					},
					{
						title: '类型',
						align: 'center',
						dataIndex: 'type_dictText',
					},
					{
						title: '数量',
						align: 'center',
						dataIndex: 'number',
					},
					{
						title: '单位',
						align: 'center',
						dataIndex: 'unit',
					},
					{
						title: '填单人',
						align: "center",
						dataIndex: 'userName',
					},
					{
						title: '送料单/领料单照片',
						align: 'center',
						width: 120,
						dataIndex: 'imgUrl',
						scopedSlots: {
							customRender: 'imgSlot'
						},
					},
					{
						title: '操作',
						dataIndex: 'action',
						align: 'center',
						fixed: 'right',
						width: 147,
						scopedSlots: {
							customRender: 'action'
						},
					},
				],
				treeData: [],
				imgList: [],
				url: {
					list: '/materials/wtMaterials/detail/list',
					add: '/materials/wtMaterials/add',
					edit: '/materials/wtMaterials/edit',
					queryById: '/materials/wtMaterials/queryById',
					delete: '/materials/wtMaterials/deleteDetail',
					wtMaterialsDetail: {
						list: '/materials/wtMaterials/queryWtMaterialsDetailByMainId',
					},
				},
				/* table加载状态 */
				loading: false,
				dataSources: [],
				footerDataSource: [],
			}
		},
		isorter: {
			column: 'createTime',
			order: 'desc',
		},
		/* 筛选参数 */
		filters: {},

		/* table选中keys*/
		selectedRowKeys: [],
		/* table选中records*/
		selectionRows: [],
		/* 查询折叠 */
		toggleSearchStatus: false,
		/* 高级查询条件生效状态 */
		superQueryFlag: false,
		/* 高级查询条件 */
		superQueryParams: '',
		/** 高级查询拼接方式 */
		superQueryMatchType: 'and',
		props: {
			//表单禁用
			disabled: {
				type: Boolean,
				default: false,
				required: false,
			},
			id: {
				type: String,
			},
		},
		computed: {
			// 数据表格的固定属性
			tableProps() {
				let tableProps = {
					size: 'middle',
					rowKey: 'rowIndex',
					columns: this.columns,
					scroll: {
						x: true
					},
				}
				let renderFooter = this.footerDataSource.length === 0 ? null : () => this.renderTableFooter(tableProps)
				return {
					...tableProps,
					ref: 'table',
					class: 'chart-data-list',
					pagination: this.pageSwitch ? this.ipagination : false,
					columns: this.columns,
					dataSource: this.dataSources,
					footer: renderFooter,
				}
			},
		},
		created() {
			//this.loadTree()
			// console.log('1234', this.id)
		},
		mounted() {
			window.onbeforeunload = function(e) {
				var storage = window.localStorage
				storage.clear()
			}
		},
		methods: {
			tolink(type, record) {
				console.log(23, type, record)
			},
			// 渲染表格底部合计行
			renderTableFooter(tableProps) {
				let h = this.$createElement
				return h('a-table', {
					ref: 'footerTable',
					props: {
						...tableProps,
						pagination: false,
						dataSource: this.footerDataSource,
						showHeader: false,
					},
				})
				//update-end---author:wangshuai ---date:20220209  for：[JTC-494]常用示例->表格合计写法改成新的写法------------
			},
			handleEdits(record) {
				this.$refs.modalForm.title = record.type == '1' ? '入库编辑' : record.type == '2' ? '出库编辑' : record.type ==
					'3' ? '直进直出编辑' : '';
				this.$refs.modalForm.pageType = 'edit';
				this.$refs.modalForm.edit(record);
				this.$refs.modalForm.disableSubmit = false;
			},
			handleXG: function(record) {
				// console.log('fds',record);
				this.$refs.modalForm1.edit(record)
			},
			handleG: function(record) {
				console.log(1, record);
				this.$refs.modalForm2.edit(record)
			},
			edit(record) {
				this.model = Object.assign({}, record)
				this.visible = true;
				this.loadData(1);
			},
			loadData(arg) {
				if (!this.url.list) {
					this.$message.error('请设置url.list属性!')
					return
				}
				//加载数据 若传入参数1则加载第一页的内容
				if (arg === 1) {
					this.ipagination.current = 1;
					this.dataSources = [];
				}
				var params = this.getQueryParams() //查询条件
				this.loading = true
				getAction(this.url.list, params).then((res) => {
						if (res.success) {
							//update-begin---author:zhangyafei    Date:20201118  for：适配不分页的数据列表------------
							this.dataSources = res.result.records || res.result
							if (res.result.total) {
								this.ipagination.total = res.result.total
							} else {
								this.ipagination.total = 0
							}
							this.dataHandling(1, this.ipagination.pageSize, this.dataSources)
							//update-end---author:zhangyafei    Date:20201118  for：适配不分页的数据列表------------
						} else {
							this.$message.warning(res.message)
						}
					})
					.finally(() => {
						this.loading = false
					})
				/* postAction(`/materials/wtMaterials/getStatisticsWtMaterialsDetail?materialsId=${this.id}`).then((res) => {
				  if (res.success) {
				    //  console.log(res)
				    this.total1 = []
				    let result = res.result
				    if(!!result){
				      this.total2.putTotal = result.putTotal
				      this.total2.outTotal = result.outTotal
				    }
				  }
				}) */
			},
			dataHandling(pageNo, pageSize, dataSource) {
				//根据当前页数和每页显示条数分割数组
				this.newDataSource = dataSource

				let arrs = [];
				//如果pageNo不是-1（不分页）,那么需要对数据进行分页计算
				if (pageNo != -1) {
					arrs = this.newDataSource.slice((pageNo - 1) * pageSize, pageNo * pageSize)
				} else {
					arrs = this.newDataSource
				}
				let newDataSource = [];
				let newArr = {};

				newArr.rowIndex = "入库合计";
				newArr.platformProductName = "出库合计";
				newArr.type_dictText = "库存合计";
				let putCount = 0; //入库
				let outCount = 0; //出库
				let invCount = 0; //库存
				//每一项的数值相加
				for (let j = 0; j < arrs.length; j++) {
					if (arrs[j].type_dictText == '入库') {
						if (!!arrs[j].number) {
							putCount += parseFloat(arrs[j].number);
						}
					}
				}
				//每一项的数值相加
				for (let j = 0; j < arrs.length; j++) {
					if (arrs[j].type_dictText == '出库') {
						if (!!arrs[j].number) {
							outCount -= parseFloat(arrs[j].number);
						}
					}
				}
				invCount = putCount + outCount;
				newArr.createTime = putCount.toFixed(3);
				newArr.model = outCount.toFixed(3);
				newArr.number = invCount.toFixed(3);
				newDataSource.push(newArr);
				//给foot底部数组赋值
				this.footerDataSource = newDataSource;
			},
			initDictConfig() {
				// console.log("--这是一个假的方法!")
			},
			handleSuperQuery(params, matchType) {
				//高级查询方法
				if (!params) {
					this.superQueryParams = ''
					this.superQueryFlag = false
				} else {
					this.superQueryFlag = true
					this.superQueryParams = JSON.stringify(params)
					this.superQueryMatchType = matchType
				}
				this.loadData(1);
			},
			getQueryParams() {
				//获取查询条件
				let sqp = {}
				if (this.superQueryParams) {
					sqp['superQueryParams'] = encodeURI(this.superQueryParams)
					sqp['superQueryMatchType'] = this.superQueryMatchType
				}
				var param = Object.assign(sqp, this.queryParam, this.isorter, this.filters)
				param.field = this.getQueryField()
				param.pageNo = this.ipagination.current
				param.pageSize = this.ipagination.pageSize
				return filterObj(param)
			},
			getQueryField() {
				var str = 'id,'
				this.columns.forEach(function(value) {
					str += ',' + value.dataIndex
				})
				return str
			},

			onSelectChange(selectedRowKeys, selectionRows) {
				this.selectedRowKeys = selectedRowKeys
				this.selectionRows = selectionRows
			},
			//搜索
			searchQuery1() {
				this.loadData(1);
			},
			//重置
			searchReset1() {
				this.queryParam = {
					materialsId: this.id,
					platformProductName: '',
					warehouseName: '',
					queryStartTime: '',
					queryEndTime: '',
					type: '',
				};
				this.loadData(1);
			}
		},
	}
</script>

<style>
	.ant-table-footer {
		padding: 5px 0px;
	}

	.count {
		width: 200px;
		height: 30px;
		/* background-color: #000; */
		margin-top: -40px;
	}

	.col1 {
		display: inline-block;
		width: 300px;
	}

	.col2 {
		display: inline-block;
		width: 55%;
		margin-left: -80px;
		margin-right: -100px;
	}
</style>